package com.accenture.portal.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.accenture.portal.model.Article;
import com.accenture.portal.model.Image;
import com.accenture.portal.model.book.BookDetail;
import com.accenture.portal.service.ImageService;

@Controller
public class ImageController
{
	@Autowired
	private ImageService ims;
	private Image image;
	
	/**
	 * 显示image后台管理页面
	 * @author chuyan.qi
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("images.action")
	public ModelAndView images (HttpServletRequest request, HttpServletResponse response, Model model) {
		return new ModelAndView ("Images");
	}
	
	/**
	 * 前台获取并显示数据库数据及分页处理
	 * @author chuyan.qi
	 * @param page
	 * @param rows
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="getjsondata.action",method=RequestMethod.GET)
	public void getjsondata(HttpServletRequest request,@RequestParam("page") int nowPageNumber,@RequestParam("rows") int nowPageSize, HttpServletResponse response) 
			throws SQLException,IOException 
	{   
		//System.out.println("pageNumber:"+nowPageNumber+",pageSize"+nowPageSize);
		//获取当前页
		if (nowPageNumber < 1) {
			nowPageNumber = 1;
		}
		//总条数
    	int total = ims.totalImage();
    	//总页数
    	int count = total/nowPageSize;
    	if (total % nowPageSize != 0) {
    		count++;
    	}
    	if (nowPageNumber > count) {
    		nowPageNumber = count;
    	}
    	List<Image> list = ims.searchImgByPage((nowPageNumber-1)*nowPageSize, nowPageSize);
        Map result = new HashMap();
		result.put("total", total);
		result.put("rows", list);
        //JSONObject ja  = JSONObject.fromObject(result);
		//System.out.println(ja.toString());
		
		JSONObject ja = new JSONObject();
		JsonConfig jf = new JsonConfig();
		jf.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		jf.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		System.out.println(ja.fromObject(result,jf).toString());		
		
		response.getWriter().write(ja.fromObject(result,jf).toString());
		response.getWriter().flush();
    }
	
	/**
	 * 日期格式化处理
	 * @author chuyan.qi
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	/**
	 * 编辑image
	 * @author chuyan.qi
	 * @param file
	 * @param imageID
	 * @param effectivetime
	 * @param editeff
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="uploadimg.action")
	public String uploadimg(@RequestParam("editfile") CommonsMultipartFile editfile,@RequestParam("imageID") int id, @RequestParam("edittime") Date time, @RequestParam("editeff") Boolean eff, HttpServletRequest request,
			ModelMap model){
		
		String fileName = editfile.getOriginalFilename();
		
		if (!fileName.endsWith(".jpg")) {
			return "failImage";
		}
		
		ServletContext sc = request.getSession().getServletContext();

		String path = sc.getRealPath("/img") + "/"; 
		System.out.println(path);
		File f = new File(path);
		if (!f.exists())
			f.mkdirs();//文件不存在建新文件
		if (!editfile.isEmpty()) {
			try {
				FileOutputStream fos = new FileOutputStream(path + fileName);
				InputStream in = editfile.getInputStream();
				int b = 0;
				while ((b = in.read()) != -1) {
					fos.write(b);
				}
				fos.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		//System.out.println("文件路径是:" + path + fileName);  
	  
		String url = path + fileName;
		url=getNewURL(url);
		image = new Image();
		image.setImgid(id);
		image.setImgurl(url);
		image.setEffectivetime(time);
		image.setEffective(eff);
		ims.uploadImg(image);
		
		
		model.addAttribute("fileUrl", url);
		
		return "Images";
	}
	
	/**
	 * image路径处理
	 * @author chuyan.qi
	 */
	private String getNewURL(String url)
	{
		int index=url.lastIndexOf("\\");
		String newString=url.substring(index+1);
		return newString;
	}
	 
	/**
	 * 删除image
	 * @author chuyan.qi
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	 @RequestMapping("deleteimg.action")
     public String delete(HttpServletRequest request,HttpServletResponse response, ModelMap model){
         String items = request.getParameter("imageid");
         List<String> delList = new ArrayList<String>();
         String[] strs = items.split(",");
         for (String str : strs) {
             delList.add(str);
         }
         ims.deleteimg(delList);
         
         return "Images";
     }
	
	 /**
		 * 添加image
		 * @author chuyan.qi
		 * @param addimgurl
		 * @param addtime
		 * @param addeff
		 * @param request
		 * @param response
		 * @param model
		 * @return
		 */
	@RequestMapping(value = "addimage.action", method = RequestMethod.POST)
	public String addimage(@RequestParam("addimgurl") CommonsMultipartFile addimgurl, @RequestParam("addtime") Date time, @RequestParam("addeff") Boolean addeff, HttpServletRequest request, ModelMap model)
	{
		
		String fileName = addimgurl.getOriginalFilename();
		
		if (!fileName.endsWith(".jpg")) {
			return "failImage";
		}

		ServletContext sc = request.getSession().getServletContext();

		String path = sc.getRealPath("/img") + "/"; 

		File f = new File(path);
		if (!f.exists())
			f.mkdirs();
		if (!addimgurl.isEmpty()) {
			try {
				FileOutputStream fos = new FileOutputStream(path + fileName);
				InputStream in = addimgurl.getInputStream();
				int b = 0;
				while ((b = in.read()) != -1) {
					fos.write(b);
				}
				fos.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String url = path + fileName;
		url=getNewURL(url);
		image = new Image();
		image.setImgurl(url);
		image.setEffectivetime(time);
		image.setEffective(addeff);
		ims.addimage(image);;
		
		model.addAttribute("fileUrl", url);
		
		return "Images";
	}
}
	